import axios from 'axios'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'// progress bar style
import { VERSION } from '@/constants/uri'
import { Notification } from 'element-ui'
import { getToken } from '../utils/auth'
NProgress.configure({ showSpinner: false })
let count = 0

axios.interceptors.request.use(function(config) {
  ++count
  config.url = VERSION + config.url
  config.headers.token = getToken()
  // config.headers.token = '0134124bcfbb433193e24af95ff1936f_e0ffdc3da63f4f1d97ecd707f873b80a'
  NProgress.start()
  return config
})

axios.interceptors.response.use(function(res) {
  handleResult(res.data)
  return res.data
}, function(error) {
  handleResult(error.response)
  return { success: false, status: error.response.status }
})

function handleResult(res) {
  if (--count === 0) {
    NProgress.done()
  }
  // 成功
  if (res.success) {
    return
  }

  // 参数错误
  if (res.status === 400) {
    Notification.error({ title: '错误', message: res.message })
    return
  }

  // 未登录
  if (res.status === 401) {
    Notification.error({ title: '错误', message: res.message })
    return
  }

  Notification.error({ title: '错误', message: res.message })
}
